package com.choosefine.base.attendance.client.record;

import com.choosefine.base.common.model.ActiveMqMessage
import com.choosefine.base.common.model.ReturnResult
import com.fasterxml.jackson.databind.ObjectMapper
import org.slf4j.Logger
import org.slf4j.LoggerFactory
import org.springframework.beans.factory.annotation.Autowired
import org.springframework.jms.core.JmsTemplate
import org.springframework.stereotype.Service

/*
*
* gen by 邱鹏 mapper 2017-08-29
*/
@Service
open class RecordService {
    val log: Logger = LoggerFactory.getLogger(RecordService::class.java)
    @Autowired lateinit var attendanceRecordDao: AttendanceRecordDao
    @Autowired lateinit var jmsTemplate: JmsTemplate
    @Autowired lateinit var jsonObjectMapper: ObjectMapper

    fun getAttendanceRecordList(attendanceRecord: AttendanceRecord): ReturnResult {
        var attendanceRecordList: List<AttendanceRecord>
        attendanceRecordList = attendanceRecordDao.findAttendanceRecordList(attendanceRecord)//查找某个节点对应的直系子女
        var result = ReturnResult(200, "获取数据成功", attendanceRecordList)
        return result
    }

    fun updateAttendanceRecord(attendanceRecord: AttendanceRecord): ReturnResult {
        var returnResult = ReturnResult()
        returnResult.status = 200
        try {
            attendanceRecordDao.updateById(attendanceRecord)
            returnResult.message = "update  AttendanceRecord成功"
        } catch (ex: Exception) {
            log.error(ex.message)
            returnResult.status = 500
            throw RuntimeException("更新AttendanceRecord出错X_X")
        } finally {
            return returnResult
        }
    }

    fun createAttendanceRecord(attendanceRecord: AttendanceRecord): ReturnResult {
        var returnResult = ReturnResult()
        returnResult.status = 200
        try {
            attendanceRecordDao.insert(attendanceRecord)
            returnResult.message = "新增attendanceRecord成功"
        } catch (ex: Exception) {
            log.error(ex.message)
            returnResult.status = 500
            throw RuntimeException("新增资源出错X_X")
        } finally {
            return returnResult
        }
    }

    fun uploadToDataCenter() {
        var attendance = AttendanceRecord().apply {
            uploadStatus = "prepared"
        }
        var recordList = attendanceRecordDao.findAttendanceRecordList(attendance)
        recordList.forEach {
            val msg = jsonObjectMapper.writeValueAsString(it)
            jmsTemplate.send("uploadAttendanceRecord", ActiveMqMessage(msg))
        }
    }
}
